package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.FightKnightDreamXmlResponse
import com.promise.jokerdream.response.phone.EventData
import com.promise.jokerdream.response.phone.EventType
import com.promise.jokerdream.response.phone.DungeonInfo
import org.jsoup.Jsoup
import java.net.URLDecoder

/**
 * 江湖长梦XML解析器
 * 用于解析江湖长梦页面中的事件链接
 */
class FightKnightDreamXmlParser : BaseXmlParser<FightKnightDreamXmlResponse>() {
    
    /**
     * 事件数据类
     */
    data class EventInfo(
        val eventId: String,
        val eventType: EventType,
        val level: Int,
        val url: String
    )
    
    /**
     * 解析江湖长梦XML数据
     * @param xmlString XML字符串
     * @return 解析结果
     */
    fun parseFightKnightDreamXml(xmlString: String): XmlParseResult<FightKnightDreamXmlResponse> {
        return parseXml(xmlString)
    }
    
    /**
     * 实现基类的具体解析逻辑
     * @param xmlString XML字符串
     * @return 解析后的江湖长梦数据
     */
    override fun doParse(xmlString: String): FightKnightDreamXmlResponse {
        val events = parseEvents(xmlString)
        val dungeonInfo = parseDungeonInfo(xmlString)
        
        return FightKnightDreamXmlResponse(
            actionResult = xmlString,
            events = events.map { event ->
                EventData(
                    eventId = event.eventId,
                    eventType = event.eventType,
                    level = event.level,
                    url = event.url
                )
            },
            dungeonInfo = dungeonInfo?.let { info ->
                DungeonInfo(
                    name = info.name,
                    currentDay = info.currentDay,
                    goldEarned = info.goldEarned
                )
            }
        )
    }
    
    /**
     * 解析XML内容，提取所有事件信息
     */
    fun parseEvents(xmlContent: String): List<EventInfo> {
        val document = Jsoup.parse(xmlContent)
        val events = mutableListOf<EventInfo>()
        
        // 查找所有包含 op=chooseEvent 的链接
        val links = document.select("a[href*='op=chooseEvent']")
        
        for (link in links) {
            val href = link.attr("href")
            val text = link.text()
            
            // 解析URL参数
            val eventId = extractEventId(href)
            val eventType = extractEventType(text)
            if (eventId != null) {
                val level = extractLevel(text)
                
                events.add(
                    EventInfo(
                        eventId = eventId,
                        eventType = eventType,
                        level = level,
                        url = href
                    )
                )
            }
        }
        
        return events
    }
    
    /**
     * 从URL中提取事件ID
     */
    private fun extractEventId(url: String): String? {
        return try {
            val decodedUrl = URLDecoder.decode(url, "UTF-8")
            val eventIdMatch = Regex("event_id=(\\d+)").find(decodedUrl)
            eventIdMatch?.groupValues?.get(1)
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 从文本中提取事件类型
     */
    private fun extractEventType(text: String): EventType {
        return when {
            text.contains("奇遇") -> EventType.ADVENTURE
            text.contains("战斗") -> EventType.BATTLE
            text.contains("商店") -> EventType.SHOP
            else -> EventType.UNKNOWN
        }
    }
    
    /**
     * 从文本中提取等级信息
     */
    private fun extractLevel(text: String): Int {
        // 匹配 "奇遇(等级2)" 或 "等级2" 格式
        val levelMatch = Regex("等级(\\d+)").find(text)
        return levelMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
    }
    
    /**
     * 解析副本信息
     */
    fun parseDungeonInfo(xmlContent: String): DungeonInfo? {
        val document = Jsoup.parse(xmlContent)
        val contentDiv = document.selectFirst("div#id")
        
        if (contentDiv != null) {
            val text = contentDiv.text()
            
            // 提取副本名称
            val nameMatch = Regex("副本名称：(.+?)\\s").find(text)
            val name = nameMatch?.groupValues?.get(1) ?: ""
            
            // 提取当前日期
            val dayMatch = Regex("当前日期：(\\d+)").find(text)
            val currentDay = dayMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
            
            // 提取获得金币
            val goldMatch = Regex("获得金币：(\\d+)").find(text)
            val goldEarned = goldMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
            
            return DungeonInfo(name, currentDay, goldEarned)
        }
        
        return null
    }
}